/**
 * 原生 canvas 类
 */
export default class Canvas {
  className = 'Canvas'; // 类名
  el = document.createElement('canvas'); // dom 元素
  constructor(config = {}) {
    // 像素比：当前显示设备的物理像素分辨率与 CSS 像素分辨率之比
    this.pixelRatio = config.pixelRatio ?? window.devicePixelRatio;
    this.width = config.width ?? 300;
    this.height = config.height ?? 150;
    this.el.setAttribute('tabindex', '0');
    this.el.setAttribute(
      'style',
      `padding: 0px;
      margin: 0px;
      border: 0px;
      background: transparent;
      display: block;
      outline: none;`,
    );
  }
  get width() {
    return parseFloat(this.el.style.width);
  }
  get height() {
    return parseFloat(this.el.style.height);
  }
  set width(val) {
    this.el.style.width = `${val}px`;
    this.el.width = val * this.pixelRatio;
  }
  set height(val) {
    this.el.style.height = `${val}px`;
    this.el.height = val * this.pixelRatio;
  }
  /**
   * Methods
   */
  /**
   * 获取 canvas 上下文
   */
  getContext() {
    return this.el.getContext('2d');
  }
  /**
   * 更新像素比
   */
  updatePixelRatio(pixelRatio = devicePixelRatio) {
    this.pixelRatio = pixelRatio;
    this.width = this.width;
    this.height = this.height;
  }
  /**
   * 销毁
   */
  destroy() {
    this.el = null;
  }
}
